<? 
error_reporting (E_ALL ^ E_NOTICE);

include('../../initDB.php');
include('../../querys.php');
include('../../functions.php');

session_start();
if ($_SESSION['log']== TRUE)
	exit(); 	

$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];

$user = magic_quotes($user);
$pass = magic_quotes($pass);
$user = escape_string($user);
$pass = escape_string($pass);	
$hash = md5($pass);

$error_messages = array(
	0 => "error: login failed.",
	1 => "error: database error.",
	2 => "error: user does not exist.",
	3 => "error: incorrrect pasword.",
	4 => "success: login successfull."
	);
	# Using a distinct errors messages for incorrect user and password
	# is an entry point for a username disclosure vulnerability.
	
$errors = array();
$response['login']['code'] = array();
$response['login']['message'] = array();

# The following should be implemented:

/*
$result = $loginQuery->execute(array(':login' => $user, ':hash' => $hash));
$rows = $loginQuery->fetchAll();
$counter = count($rows);
echo "<br> Count2 = $counter";*/

# Check if user exists
$resultQuery = $retrieveUser->execute(array($user));
$result = $retrieveUser->fetchAll();
	if ($resultQuery != FALSE) {
		if(count($result) != 1)
			array_push($errors, 2);
	}
	else
		array_push($errors, 1);
		
# Check if password matches
$result3 = $db->query("SELECT * from passwords where hashP = '$hash' and userID = (SELECT id FROM users where name = '$user')");

# Can't use this prepared statement
#$loginQuery->execute(array(':login' => $user, ':hash' => $hash));
#$result2 = $loginQuery->fetchAll();
#echo "count: " . count($result2);

if (count($result3->fetchAll()) == 1) {

	$bool = session_start();
	$_SESSION['log'] = TRUE;
	$_SESSION['user'] = $user;
	$_SESSION['hash'] = $hash;
	
	array_push($response['login']['code'], 4);
	array_push($response['login']['message'], $error_messages[4]);
	
	#header("Refresh: 2;url=login_success.php");
}
else 
	array_push($errors, 3);
	

if (sizeof($errors)) {
	
	array_push($response['login']['code'], 0);
	array_push($response['login']['message'], $error_messages[0]);
	
	foreach ($errors as $code) {
		array_push($response['login']['code'], $code);
		array_push($response['login']['message'], $error_messages[$code]);
	}
	#header("Refresh: 2; url=login_error.php");
	# Increment max tries for a user
}
	print_output($response);
?>